/**
 * @description: ja简易版，外包专用，beta阶段
 * @update: 2019-07-10
 * @version: 1.0
 **/
/**
 * == plat ==
 * 支持：changyou(畅游) phone(手机) warframe(星际战甲) wechat(微信) cyou3(橙柚三联)
 * 不支持： changyoujia(畅游加) dj(刀剑) Anonymous(匿名访问)
 */
'use strict';

(function () {
    var that;
    var name = 'cyja';
    var version = '1.0';
    var JoinActivity = function () {
        // -----------------全局变量----------------
        this.options = {
            app: undefined,             // 应用 初始化必传项
            activity: undefined,        // 活动 初始化必传项
            version: undefined,         // 版本 初始化必传项
            server: undefined,          // 服务 初始化必传项
            platform: undefined,        // 平台 初始化必传项

            isUserInit: false,          // 获取用户信息初始化
            isWxLogin: false,           // 是否微信授权(暂时关闭)
            isWxInit: false,            // 微信初始化(暂时关闭)
            isWxDebug: false,           // 是否开启微信debug调试(暂时关闭)
            wxShare: undefined,         // 微信分享内容
            host: location.origin,      // 接口请求域名，默认同域名
            appId: undefined,           // 微信 appId 手动添加，优先 init 接口的 wxId

            ready: function() {},       // 初始化完成后执行
        };
        this.glob = {
            isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
            isWechat: window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger',
            arrEnable: ['app', 'activity', 'version', 'server', 'platform'],    // 必传项
            cyscid: this.utils.getQueryString('CYSCID') || undefined,           // 地址标识
            token: undefined,           // token
            code: 0,                    // 初始化状态：0 初始化未完成;1 初始化成功;2 活动未开始;3 活动已结束;4 用户未登录
            userInfo: undefined,        // 用户信息
            wechatInfo: undefined,      // 微信用户信息
        };
        that = this;
    };
    JoinActivity.fn = JoinActivity.prototype = {
        // -----------------初始化----------------
        config: function(options)   {
            $.extend(this.options, options);
            if(this.admin.enable()) {
                that.user.getToken(function(res) {
                    if(res.code === 10000) {
                        if((that.options.platform !== 'wechat' && that.glob.isWechat && that.options.isWxLogin) || that.options.platform === 'wechat') {
                            that.user.getUserInfo('wechat', function() {
                                that.admin.manage();
                            });
                        }else {
                            that.admin.manage();
                        }
                    }else {
                        that.options.ready(that.glob);
                    }
                })
            }
        },
        // -----------权限(辅助config参数判断)----------------
        admin: {
            enable: function() {
                var isPass = true
                    , arrMust = that.glob.arrEnable;
                // 必填项
                arrMust.forEach(function (item, index) {
                    if(!that.options[item]) {
                        alert(item + '为必填项');
                        arrMust = arrMust.concat(arrMust.splice(index, arrMust.length - index));
                        isPass = false;
                    }
                });
                if(that.options.platform === 'wechat' && !that.glob.isWechat) {
                    alert('请在微信中访问');
                    isPass = false;
                }
                return isPass;
            },
            manage: function() {
                if(that.glob.isWechat) {
                    if(that.options.isWxInit) {
                        that.wx.init(function() {
                            if(that.options.wxShare) that.wx.share(that.options.wxShare);
                        })
                    }
                }
                if(that.options.isUserInit) {
                    that.user.getUserInfo(that.options.platform, that.options.ready)
                }else {
                    that.options.ready(that.glob);
                }
            },
            error: function(msg) {
                console.log(name + version + '提示: ' + msg);
            }
        },
        // ----------------- 工具类 ----------------
        utils: {
            // 截取url参数
            getQueryString: function(name) {
                var reg = new RegExp('(^|&)'+ name +'=([^&]*)(&|$)');
                var r = window.location.search.substr(1).match(reg);
                if(r!=null)return  unescape(r[2]); return null;
            },
            isJSON: function(str) {
                if (typeof str == 'string') {
                    try {
                        var obj = JSON.parse(str);
                        if(typeof obj == 'object' && obj ){
                            return true;
                        }else{
                            return false;
                        }

                    } catch(e) {
                        return false;
                    }
                }
            },
            // 弹窗
            win: {
                scrolling: 'no',
                //是否显示滚动条 no,yes,auto
                int: function () {
                    $("#winClose").on('mouseenter',
                        function () {
                            $(this).css("background-image", "url()");
                        });
                    $("#winClose").on('mouseleave',
                        function () {
                            $(this).css("background-image", "url()");
                        });
                    $("#winClose").on('click',
                        function () {
                            $("#mask,#maskTop").fadeOut(function () {
                                $(this).remove();
                            });
                        });
                },
                open: function (width, height, src) {
                    var iframeHeight = height;
                    var marginLeft = width / 2;
                    var marginTop = height / 2;
                    var inntHtml = '';
                    inntHtml += '<div id="mask" style="width:100%; height:100%; position:fixed; top:0; left:0; z-inde:1999;background:#cccccc; filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity:0.5;"></div>';
                    inntHtml += '<div id="maskTop" style="width: ' + width + 'px; height: ' + height + 'px;  color: #333; position: fixed; top: 50%; left: 50%; margin-left: -' + marginLeft + 'px; margin-top: -' + marginTop + 'px; z-index: 2999; ">';
                    inntHtml += '<div id="maskTitle" style="height: 0;position: relative;">';
                    inntHtml += '<div id="winClose" style="width: 28px; height: 28px; cursor: pointer; position: absolute; top: -12px; right: -9px; background-image: url();"></div>';
                    inntHtml += '</div>';
                    inntHtml += '<iframe width="' + width + '" height="' + iframeHeight + '" frameborder="0" scrolling="' + this.scrolling + '" src="' + src + '"></iframe>';
                    inntHtml += '</div>';
                    $("body").append(inntHtml);
                    this.int();
                },
                close: function () {
                    $("#winClose").click();
                }
            },
            // cookie操作
            cookie: {
                get: function(cname) {
                    var name = cname + '=';
                    var ca = document.cookie.split(';');
                    for(var i=0; i<ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0)==' ') c = c.substring(1);
                        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
                    }
                    return '';
                },
                set: function(cname, cvalue, exdays, domain) {
                    var d = new Date();
                    d.setTime(d.getTime() + (exdays*24*60*60*1000));
                    var expires = 'expires='+d.toUTCString();
                    document.cookie = cname + '=' + cvalue + '; ' + expires + '; domain=' + domain + '; path=/';
                },
                del: function(name, domain) {
                    this.set(name, '', -1, domain);
                }
            },
            session: {
                set: function(name, value) {
                    if(Object.prototype.toString.call(value) === '[object object]') value = JSON.stringify(value);
                    sessionStorage.setItem(name, value)
                },
                get: function(name) {
                    var value = sessionStorage.getItem(name);
                    return that.utils.isJSON(value) ? JSON.parse(value) : value;
                },
                remove: function(name) {
                    sessionStorage.removeItem(name);
                },
                clear: function() {
                    sessionStorage.clear();
                }
            }
        },
        // -----------------ajax请求----------------
        client: {
            ajax: function (type, url, data, fun) {
                $.ajax({
                    type: type,
                    url: url,
                    data: data,
                    dataType: 'json',
                    headers: {
                        'Authorization': that.glob.token,
                        'APP': that.options.app,
                        'ACTIVITY': that.options.activity,
                        'VERSIONCODE': that.options.version,
                        'PLAT': that.options.platform,
                        'CYSCID': that.glob.cyscid
                    },
                    success: function(res) {
                        fun(res)
                    }
                })
            },
            basePath: function(plat, host) {
                var base = (host || that.options.host) + '/wb/' + that.options.server;
                if(plat) base += ('/' + plat);
                return base;
            },
            get: function(url, data, fun, plat) {
                this.ajax('GET', this.basePath(plat) + url, data, fun);
            },
            post: function(url, data, fun, plat) {
                this.ajax('POST', this.basePath(plat) + url, data, fun);
            },
        },
        // -----------------用户登陆----------------
        user: {
            url: {
                core: function() {
                    return '/core/login/' + that.options.app + '/' + that.options.activity + '/' + that.options.version;
                },
                tokenPath: '/init',                 // 获取token
                phoneCodePath: '/sendcode',         // 登陆发送手机号验证码
                loginPhonePath: '/phonelogin',      // 手机号登录
                userInfoPath: '/user/info'          // 用户详情
            },
            // 获取token
            getToken: function(fun) {
                that.client.get(this.url.tokenPath, {}, function (res) {
                    switch (res.code) {
                        case 10000:             // 初始化正常
                            if(!that.options.isUserInit) that.glob.code = 1;
                            that.glob.token = res.data.token;
                            if(!that.options.appId && res.data.wxId !== '0') that.options.appId = res.data.wxId;
                            break;
                        case 1106:             // 活动未开始
                            that.glob.code = 2;
                            break;
                        case 1103:             // 活动已结束
                            that.glob.code = 3;
                            break;
                        case 1102:             // 活动无效
                            alert(res.message);
                            break;
                        default:                // 其他
                            that.glob.code = 99;
                            alert(res.message);
                            break;
                    }
                    fun && fun(res);
                }, that.options.platform)
            },
            // 获取验证码
            getCode: function(phone, fun) {
                that.client.post(this.url.phoneCodePath, {
                    phone: phone
                }, function(res) {
                    fun ? fun(res) : alert(res.code === 10000 ? '验证码发送成功' : res.message);
                }, 'phone');
            },
            // 手机号与验证码登陆
            loginPhone: function(phone, code, fun) {
                that.client.post(this.url.core() + this.url.loginPhonePath, {
                    phone: phone,
                    code: code
                }, function(res) {
                    fun ? fun(res) : res.code === 10000 ? location.reload() : alert(res.message);
                }, 'phone');
            },
            // 是否绑定微信
            wxIsBind: function(fun) {
                that.client.post('/auto/isbind', {}, function(res) {
                    fun(res);
                }, 'wechat')
            },
            wxAutoLogin: function(fun) {
                that.client.post('/auto/autologin', {}, function(res) {
                    fun(res);
                }, 'wechat')
            },
            // 打开登录界面
            login: function(platform, back) {
                var plat = platform || that.options.platform
                    , url = that.client.basePath(plat) + this.url.core() + '/login?callback=' + encodeURI(back || location.href)
                    // , djurl = that.client.basePath(plat) + this.url.core() + '/djlogin?callback=' + encodeURI(back || location.href)
                    , isMobile = that.glob.isMobile
                    , isWechat = that.glob.isWechat;
                switch (plat) {
                    case 'warframe':case 'changyou':
                        isMobile ? window.location.href = url : that.utils.win.open(490, 352, url);
                        break;
                    case 'cyou3':
                        isMobile ? window.location.href = url : that.utils.win.open(490, 470, url);
                        break;
                    case 'dj':
                        // isMobile ? window.location.href = djurl : that.utils.win.open(490, 352, url);
                        // djLogin()
                        break;
                    case 'wechat':
                        isWechat && (window.location.href = url);
                        break;
                    case 'phone':
                        alert('请先登录');
                        break;
                    default:
                        alert('暂时还没有该平台登陆功能');
                }
            },
            // 获取用户信息
            getUserInfo: function(plat, fun) {
                that.client.get(this.url.userInfoPath, {}, function(res) {
                    if(plat === 'wechat') {
                        if(res.code === 10000) {
                            that.glob.wechatInfo = res.data;
                            if(that.options.platform === 'wechat') that.glob.code = 1;
                        }else {
                            if(that.options.platform === 'wechat') {
                                that.glob.code = 4;
                            }else {
                                that.user.login('wechat');
                            }
                        }
                    }else {
                        if(res.code === 10000) {
                            that.glob.userInfo = res.data;
                            that.glob.code = 1;
                        }else {
                            that.glob.code = 4;
                        }
                    }
                    fun && fun(that.glob);
                }, plat || that.options.platform);
            },
            // 登出
            logout: function (fun) {
                if(that.glob.isWechat &&  (that.options.isWxLogin || that.options.platform === 'wechat')) {
                    this.logoutWx()
                }else {
                    this.logoutAct(fun);
                }
            },
            // 微信登出
            logoutWx: function() {
                that.client.post('/auto/cancel', {}, function(res) {
                    if(res.code === 10000) {
                        that.user.logoutAct();
                    }
                }, 'wechat')
            },
            logoutAct: function(fun) {
                that.client.post(this.url.core() + '/logout', {}, function (res) {
                    if(res.code === 10000) {
                        if(['changyou', 'warframe', 'wechat'].indexOf(that.options.platform) !== -1) {
                            that.utils.cookie.del('CASGTC', '.changyou.com');
                            // location.href = 'https://auth.changyou.com/logout.jsp?b=' + location.href.split("#")[0] + '&co=' + that.utils.cookie.get("CASGTC");
                        }
                        fun || location.reload();
                    }
                }, that.options.platform);
            }
        },
        // -----------------微信业务----------------
        wx: {
            // 微信初始化
            init: function(fun) {
                if(!that.options.appId) {
                    that.admin.error('微信初始化失败，没有得到 wxId');
                    return false;
                }
                if(typeof wx === 'undefined') {
                    that.admin.error('微信初始化失败，请引入 https://res.wx.qq.com/open/js/jweixin-1.4.0.js');
                    return false;
                }
                $.ajax({
                    url: that.client.basePath('wechat') + '/' + that.options.appId + '/config?_=' + Date.now(),
                    success: function(data) {
                        if(data.config) {
                            wx.config({
                                debug: that.glob.isWxDebug ,        // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                appId: data.config.appId,           // 必填，公众号的唯一标识
                                timestamp: data.config.timestamp,   // 必填，生成签名的时间戳
                                nonceStr: data.config.nonceStr,     // 必填，生成签名的随机串
                                signature: data.config.signature,   // 必填，签名，见附录1
                                jsApiList: [                        // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                                    'translateVoice',
                                    'onMenuShareTimeline',
                                    'onMenuShareAppMessage',
                                    'onMenuShareQQ',
                                    'onMenuShareWeibo',
                                    'hideMenuItems',
                                    'hideAllNonBaseMenuItem',
                                    'onMenuShareQZone'
                                ]
                            });
                            fun && fun();
                        }else {
                            that.admin.error('微信初始化失败，' + data.msg);
                        }
                    }
                });
            },
            // 分享
            share: function(options) {
                var _options = {
                    type: 'link',
                    shareList: [
                        'onMenuShareTimeline',      // 分享到朋友圈
                        'onMenuShareAppMessage',    // 分享给朋友
                        'onMenuShareQQ',            // 分享到QQ
                        'onMenuShareWeibo',         // 分享到腾讯微博
                        'onMenuShareQZone'          // 分型到QQ空间
                    ]
                };
                _options = $.extend(_options, options);
                var list = _options.shareList;
                delete _options['shareList'];
                wx.ready(function() {
                    for(var i in list) {
                        var shareType = list[i];
                        if($.isFunction(wx[shareType])) {
                            wx[shareType](_options);
                        }
                    }
                })
            }
        }
    };
    window[name] = new JoinActivity();
}());
